$(document).ready(function (){
    layui.use(['laytp'], function() {
        var token = facade.getCookie('token');
        if(token == undefined || token == '' || !token){
            facade.redirect("/login.php");
        }
    });
    $(document).mousemove(function () {
        top.parent.seconds = 900;
    });
    $(document).keydown (function () {
        top.parent.seconds = 900;
    });

    // 禁止滑轮滚动
    $('input[type="number"]').attr('onmousewheel','return false;');


    // 时间选择
    $('.bdate_y').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy',//显示格式
        startView: '4',
        minView: "4",//设置只显示到月份
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true//显示今日按钮
    }).on('changeDate',editPageCheck);

    $('.bdate_ym').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm',//显示格式
        startView: '3',
        minView: "3",//设置只显示到月份
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true//显示今日按钮
    }).on('changeDate',editPageCheck);

    $('.bdate_ymd').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm-dd',//显示格式
        minView: "month",//设置只显示到月份
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true,//显示今日按钮
    }).on('changeDate',editPageCheck);

    $('.bdate_ymdhi').datetimepicker({
        language: 'zh-CN',//显示中文
        format: 'yyyy-mm-dd hh:ii',//显示格式
        initialDate: new Date(),//初始化当前日期
        autoclose: true,//选中自动关闭
        todayBtn: true//显示今日按钮
    }).on('changeDate',editPageCheck);

    //
    $('body').on('click','.short_table_list .layui-form-select',function () {
        var width = $(this).width() - 6;
        var top = $(this).offset().top - $(window).scrollTop();
        var left = $(this).offset().left;
        $(this).find('dl').css('cssText',"width:"+width+"px !important;min-width:"+width+"px !important;top:"+top+"px;left:"+left+"px;overflow-x: hidden;");
        $(this).find('dd').css('cssText',"width:"+width+"px !important;");
    });

    // 详情页td宽度
    // var tdw = ($('#showBox').width() - 270) / 2;
    // $('#showBox .table-box .table-detail tr td:nth-of-type(even)').css('width',tdw+'px');
});



function editPageCheck() {
    try {
        $("#commentForm").valid();
    }catch (e) {

    }
    try {
        $("#operatePage").valid();
    }catch (e) {

    }
}


/**
 * 获取url参数
 * @param variable
 * @returns {*}
 */
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return false;
}

function in_array(search,array){
    for(var i in array){
        if(array[i]==search){
            return true;
        }
    }
    return false;
}

function render_from(){
    layui.use(['form','table'],function(){
        var form = layui.form;
        form.render("select");
        form.render("checkbox");
        form.render("radio");

        $('.xmselect_title').remove();

        $('input[type="number"]').attr('onmousewheel','return false;');
    });
}


function render_input_attr(){
    layui.use(['inputAttr'],function(){
        var inputAttr = layui.inputAttr;
        inputAttr.render({
            root: ".layui-form",
            matchRule: "input,textarea[maxlength]",
            // 事件托管
            event: {
                clearable: function (event, dom) {
                },
            },
        });
    });
}
// 动态ele初始化
function render_inputAttr(dom){
    layui.use(['inputAttr'],function(){
        var inputAttr = layui.inputAttr;
        inputAttr.render({
            root: dom,
            matchRule: "input,textarea[maxlength]",
            // 事件托管
            event: {
                clearable: function (event, dom) {
                },
            },
        });
    });
}




function openNavPage(title='', url, id) {
    if(!id){
        id = parseInt(Math.random()*10000000000);
    }
    url = '/page/'+url;
    top.parent.bodyTab.addTabOnly({
        id: id,
        title: title,
        url: url,
        icon: "",
        close: true
    }, 300);
}



/**
 * 打开一个新的页面
 * @param obj
 */
function openNewPage(obj, key) {
    layui.use(['element','laytpTab'], function() {
        var element = layui.element;
        var laytpTab = layui.laytpTab;
        var menu_id = obj.id;
        var menu_href = '/page/'+obj.href;
        var menu_title = obj.title;
        var menu_pid = obj.pid;
        localStorage.setItem('active_er_menu'+menu_pid, menu_id);
        if(key == undefined){
            localStorage.setItem('active_er_menu_key', '');
        }else{
            localStorage.setItem('active_er_menu_key', key);
        }

        var isData = false;
        $.each($(".layui-tab[lay-filter='content'] .layui-tab-title li[lay-id]"), function() {
            if ($(this).attr("lay-id") == menu_id) {
                isData = true;
            }
        });
        if(isData == false){
            laytpTab.render({
                elem: 'content',
                roll: true,
                tool: true,
                width: '100%',
                height: '100%',
                index: 2,
                id: menu_id,
                url: menu_href,
                title: menu_title,
                close: true,
                news: 1, // 是否为新增
            });
        }else{
            element.tabChange('content', menu_id);
        }
    });
}



function open_page(url,title,width,height){
    if(width == undefined || width == ''){
        width = '80%';
    }
    if(height == undefined || height == ''){
        height = '80%';
    }
    var index = layer.open({
        type: 2,
        title: [title,'background-color:#ffffff;'],
        area: [width, height],
        // btn:[],
        maxmin: true,
        content: url,
    });
}

function openPage(url, width, height) {
    if(width == undefined || width == ''){
        width = '100%';
    }
    if(height == undefined || height == ''){
        height = '100%';
    }
    layer.open({
        title: false
        ,skin: 'operate-layer'
        ,type: 2
        ,content: url
        ,area: [width, height]
        ,closeBtn: 0
        ,move: '.move_title'
        ,moveOut: true
    });
}

function openPageRight(url, width, height, shade=0.3) {
    if(width == undefined || width == ''){
        width = '100%';
    }
    if(height == undefined || height == ''){
        height = '100%';
    }
    layer.open({
        title: false
        ,skin: 'operate-layer'
        ,type: 2
        ,offset: 'r'
        ,shade: shade
        ,content: url
        ,area: [width, height]
        ,closeBtn: 0
        ,move: '.move_title'
        ,moveOut: true
    });
}

function openPageEdit(url, width, height) {
    if(width == undefined || width == ''){
        width = '100%';
    }
    if(height == undefined || height == ''){
        height = '100%';
    }
    layer.open({
        title: false
        ,skin: 'operate-layer'
        ,type: 2
        ,content: url
        ,area: [width, height]
        ,closeBtn: 0
        ,move: '.move_title'
        ,moveOut: true
    });
}
function openParentPageEdit(url, width, height) {
    if(width == undefined || width == ''){
        width = '100%';
    }
    if(height == undefined || height == ''){
        height = '100%';
    }
    parent.layer.open({
        title: false
        ,skin: 'operate-layer'
        ,type: 2
        ,content: url
        ,area: [width, height]
        ,closeBtn: 0
        ,move: '.move_title'
        ,moveOut: true
    });
}


function openPageMain(url, width, height) {
    if(width == undefined || width == ''){
        width = '100%';
    }
    if(height == undefined || height == ''){
        height = '100%';
    }
    top.parent.layer.open({
        title: false
        ,skin: 'operate-layer'
        ,type: 2
        ,content: url
        ,area: [width, height]
        ,closeBtn: 0
        ,move: '.move_title'
        ,moveOut: true
    });
}



/**
 * 关闭弹窗
 */
function layer_close(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}
function layer_close_opt(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}


function choose_close(obj, dom = '', msg = '') {
    $(obj).parent().remove();
    if(dom){
        if(msg !== '') {
            formValid(dom, msg);
        }else{
            formValid(dom);
        }
        var callback = 'choose_'+dom+'_delete';
        if(typeof(window[callback]) != 'undefined'){
            window[callback]();
        }
    }

    // 关联单据 样式处理
    var h = $("#"+dom).height();
    if(h < 29){
        h = 30;
    }
    $("."+dom).css('cssText','height:'+ (h+5) +'px !important');
}



function xmselect_dan(dom, data, value, callback) {
    layui.use(['xmSelect'], function() {
        var xmSelect = layui.xmSelect;

        var xmObj = xmSelect.render({
            el: '#'+dom,
            autoRow: true,
            initValue: [value],
            name: dom,
            filterable: true,
            clickClose: true,
            radio: true,
            // model: { label: { type: 'text' } },
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: true,
                strict: false,
            },
            theme: {
                color: '#2272eb',
            },
            // toolbar: {
            //     show: true,
            //     list: ['ALL', 'REVERSE', 'CLEAR']
            // },
            height: 'auto',
            data: data,
            on: function(data){
                if(callback){
                    callback(data);
                }
            },
        })

    });
}

function xmselect_duo(dom, data, value, callback) {
    layui.use(['xmSelect'], function() {
        var xmSelect = layui.xmSelect;

        var xmObj = xmSelect.render({
            el: '#'+dom,
            name: dom,
            autoRow: true,
            filterable: true,
            initValue: value,
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: true,
                strict: false,
            },
            theme: {
                color: '#2272eb',
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            height: 'auto',
            data: data,
            on: function(data){
                if(callback){
                    callback(data);
                }
            },
        })

    });
}


function xmselect_list_dan(dom, data, value, callback) {
    layui.use(['xmSelect'], function() {
        var xmSelect = layui.xmSelect;

        var xmObj = xmSelect.render({
            el: '.'+dom,
            autoRow: true,
            initValue: [value],
            name: dom,
            filterable: true,
            radio: true,
            // model: { label: { type: 'text' } },
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: true,
                strict: false,
            },
            theme: {
                color: '#2272eb',
            },
            // toolbar: {
            //     show: true,
            //     list: ['ALL', 'REVERSE', 'CLEAR']
            // },
            height: 'auto',
            data: data,
            on: function(data){
                if(callback){
                    callback(data);
                }
            },
        })

    });
}

function xmselect_list_duo(dom, data, value, callback) {
    layui.use(['xmSelect'], function() {
        var xmSelect = layui.xmSelect;

        var xmObj = xmSelect.render({
            el: '.'+dom,
            name: dom,
            autoRow: true,
            filterable: true,
            initValue: value,
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 20,
                expandedKeys: true,
                strict: false,
            },
            theme: {
                color: '#2272eb',
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            height: 'auto',
            data: data,
            on: function(data){
                if(callback){
                    callback(data);
                }
            },
        })

    });
}

function dataPostTimeOut(tabid='datalist',time=1500) {
    facade.success("提交成功!");
    setTimeout(() => {
        try {
            parent.layui.table.reload('datalist');
        }catch (e) {

        }
        layer_close_opt();
    }, time);
}


function parOtherSonPage(url) {
    top.layer.closeAll();
    top.parent.openPage(url, '80%', '80%')
}


function dataFolwPostTimeOut(data=[], tabid='datalist',time=3000) {
    if(data.isturn == 0){
        facade.success("暂存成功，请至流程-草稿中查看或编辑");
        parent.parOtherSonPage('/page/bill_turn/wel.php');
    }else{
        facade.success("提交成功!");
    }

    setTimeout(() => {
        try {
            parent.layui.table.reload('datalist');
        }catch (e) {

        }
        layer_close_opt();
    }, time);
}



function public_flow_submit(data=[], addUrl, editUrl, but) {
    if(but == 1){
        var chTime = getChineseDateTime();
        if(data.id){
            data.isshen = 0;
            facade.ajax({url: editUrl, data:data}).done(function(res){
                facade.success("已于 "+chTime+" 保存为草稿");
            });
        }else{
            facade.ajax({url: addUrl, data:data}).done(function(res){
                if (res.code === 2000) {
                    facade.success("已于 "+chTime+" 保存为草稿");
                    $("form").find('.main-container').append('<input type="hidden" id="billid" name="id" value="'+res.data.billid+'">');
                }
            });
        }
    }

    if(but == 2){
        layer.confirm("<div class='tit'>是否将此申请单据存为草稿？</div><div class='exp'>存为草稿后可在“我的-流程-草稿”中继续编辑或提交</div>", {
                title:'操作确认',
                icon: 3,
                area:['450px','220px'],
                btn:['确定']
            }, function(conindex){
                if(data.id){
                    data.isshen = 0;
                    facade.ajax({url: editUrl, data:data}).done(function(res){
                        if (res.code === 2000) {
                            facade.success("保存草稿成功!");
                            setTimeout(() => {
                                try {
                                    parent.layui.table.reload('datalist');
                                }catch (e) {

                                }
                                layer_close_opt();
                            }, 3000);
                        }
                        layer.close(conindex)
                    });
                }else{
                    facade.ajax({url: addUrl, data:data}).done(function(res){
                        if (res.code === 2000) {
                            facade.success("保存草稿成功!");
                            setTimeout(() => {
                                try {
                                    parent.layui.table.reload('datalist');
                                }catch (e) {

                                }
                                layer_close_opt();
                            }, 3000);
                        }
                        layer.close(conindex)
                    });
                }
            }
        )
    }

    if(but == 3){
        layer.confirm("<div class='tit'>是否将此申请单据提交审批？</div><div class='exp'>提交之后可在“我的-流程-我发起的”中查询审批进度</div>", {
                title:'操作确认',
                icon: 3,
                area:['450px','220px'],
                btn:['确定']
            }, function(conindex){
                if(data.id){
                    if(data.isshen == undefined){
                        data.isshen = 0;
                    }
                    facade.ajax({url: editUrl, data:data}).done(function(res){
                        if (res.code === 2000) {
                            facade.success("提交成功!");
                            setTimeout(() => {
                                try {
                                    parent.layui.table.reload('datalist');
                                }catch (e) {

                                }
                                layer_close_opt();
                            }, 3000);
                        }
                        layer.close(conindex)
                    });
                }else{
                    facade.ajax({url: addUrl, data:data}).done(function(res){
                        if (res.code === 2000) {
                            facade.success("提交成功!");
                            setTimeout(() => {
                                try {
                                    parent.layui.table.reload('datalist');
                                }catch (e) {

                                }
                                layer_close_opt();
                            }, 3000);
                        }
                        layer.close(conindex)
                    });
                }
            }
        )
    }


}










function data_delete(url, data, tit='', exp='', width='', height=''){
    if(!tit){
        tit = '是否确认删除？';
    }
    if(!exp){
        exp = '删除后不可恢复，请谨慎删除';
    }
    if(!width){
        width = '450px';
    }
    if(!height){
        height = '220px';
    }
    layer.confirm("<div class='tit'>"+tit+"</div><div class='exp'>"+exp+"</div>", {
            title:'操作确认',
            icon: 3,
            area:[width,height],
            btn:['确定']
        }, function(conindex){
            facade.ajax({url: url, data:data}).done(function(res){
                if (res.code === 2000) {
                    facade.success("提交成功!");
                    try {
                        layui.table.reload('datalist');
                        layui.use(['table','form'], function () {
                            var table = layui.table,form = layui.form;
                            searchTableFunc(form, table);
                        })
                    }catch (e) {

                    }
                    layer.close(conindex);
                }
            });
        }
    )
}

function data_public_confirm(url, data, tit='', exp='', width='', height=''){
    if(!width){
        width = '450px';
    }
    if(!height){
        height = '220px';
    }
    layer.confirm("<div class='tit'>"+tit+"</div><div class='exp'>"+exp+"</div>", {
            title:'操作确认',
            icon: 3,
            area:[width,height],
            btn:['确定']
        }, function(conindex){
            facade.ajax({url: url, data:data}).done(function(res){
                if (res.code === 2000) {
                    facade.success("提交成功!");
                    try {
                        layui.table.reload('datalist');
                        layui.use(['table','form'], function () {
                            var table = layui.table,form = layui.form;
                            searchTableFunc(form, table);
                        })
                    }catch (e) {

                    }
                    layer.close(conindex);
                }
            });
        }
    )
}

function get_file_complete(encpath) {
    return server_api_name+ask_show_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
}
function get_bao_file_complete(encpath) {
    return server_api_name+ask_show_bao_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
}
function get_temp_file_complete(encpath) {
    return server_api_name+ask_show_temp_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
}
function get_ban_file_complete(encpath) {
    return server_api_name+ask_show_ban_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
}
function get_engin_file_complete(encpath) {
    return server_api_name+ask_show_engin_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
}

function public_upload_file_load222(dom, data=[], tits='附件信息') {
    $("#"+dom).find('.upload-tits').text(tits);
    if(data.length > 0){
        upload_files_edit_data(dom, data);
    }else{
        // $("#"+dom).find('.upload_files_tbody').html('<tr id="nofile"><td colspan="7" style="text-align: center;border: 0;">暂无附件</td></tr>')
        $("#"+dom).find('.upload_files_tbody').html('<tr id="nofile"><td colspan="7" style="text-align: center;border: 0;"><div><div><img style="width:70px;" src="/static/admin/images/welnodata.png" /></div><span class="addfile upload_file_btn" style="cursor: pointer;">+上传附件</span></div></td></tr>')

    }
    $("#"+dom).find('.upload_file_btn').click(function () {
        upload_files_file_btn(dom);
    });
    upload_files_init_mouse(dom);
    upload_files_qiehuan(dom)
}

function public_upload_file_load(dom, data=[], tits='附件信息') {
    if(data.length > 0){
        upload_files_edit_data(dom, data);
    }
    $("#"+dom).find('.upload_file_btn').click(function () {
        upload_files_file_btn(dom);
    });
}

function public_upload_file_value(dom) {
    var files = [''];
    $('#'+dom+' #fileboxss .filebb').each(function(){
        if($(this).attr('id')){
            files.push({id: $(this).attr('id'), fileplain: $(this).find('.fileplain').val()});
        }
    });
    return files;
}

function public_upload_file_value_str(dom) {
    var files = '0';
    $('#'+dom+' #fileboxss .filebb').each(function(){
        var fileid = parseInt($(this).attr('id'));
        if(fileid){
            files += ','+fileid;
        }
    });
    return files;
}

function upload_files_edit_data222(dom, data) {
    for (var key in data){
        var id = data[key].id;
        var filename = data[key].name;
        var filepath = data[key].encpath;
        var fileurl = get_file_complete(filepath);
        var fileext = data[key].ext;
        var filesize = data[key].size;
        var fileplain = data[key].fileplain;
        var created_user = data[key].created_user_name;
        var created_at = data[key].created_at;
        var str = '';
        var trNum =  parseInt(key)+1;
        str += '<tr id='+id+'>';
        str += '<td>'+trNum+'</td>';
        str += '<td>'+filename+'</td>';
        str += '<td><input type="text" class="layui-input fileplain" value="'+fileplain+'" placeholder="说明..."></td>';
        str += '<td>'+filesize+'KB</td>';
        str += '<td>'+created_at+'</td>';
        str += '<td>'+created_user+'</td>';
        str += '<td class="opt">';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            str += '<a onclick="upload_files_viewer_img_show(\''+dom+'\')">查看</a>';
        }
        if(fileext == 'pdf'){
            str += '<a onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')">查看</a>';
        }
        if(fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx'){
            str += '<a onclick="upload_files_vieweroffice_show(\''+fileurl+'\')">查看</a>';
        }
        str += '<a onclick="upload_files_del_file(\''+dom+'\','+id+')">删除</a>';
        str += '</td>';
        str += '</tr>';
        $('#'+dom+' .upload_files .table_show tbody').append(str);


        var imgstr = '';
        imgstr += '<div class="li" id='+id+'>';
        imgstr += '<div class="imgdiv">';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            imgstr += '<img src="'+fileurl+'" data_src="'+fileurl+'">';
        }else if(fileext == 'pdf'){
            imgstr += '<div class="dea-ext" onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')">'+fileext+'</div>';
        }else if(fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx'){
            imgstr += '<div class="dea-ext" onclick="upload_files_vieweroffice_show(\''+fileurl+'\')">'+fileext+'</div>';
        }else{
            imgstr += '<div class="dea-ext">'+fileext+'</div>';
        }
        imgstr += '</div>';
        imgstr += '<div class="filetit">'+filename+'</div>';
        imgstr += '<span class="cheng">';
        imgstr += '<i class="fa fa-times-circle shan" onclick="upload_files_del_file(\''+dom+'\','+id+')"></i>';
        imgstr += '</span>';
        imgstr += '</div>';
        $('#'+dom+' .upload_files .image_show').append(imgstr);
    }
    upload_files_file_viewer(dom)
    upload_files_init_mouse(dom);
}
function upload_files_edit_data(dom, data) {
    for (var key in data){
        var id = data[key].id;
        var filename = data[key].name;
        var filepath = data[key].encpath;
        var fileurl = get_file_complete(filepath);
        var fileext = data[key].ext;
        var filesize = data[key].size;
        var fileplain = data[key].fileplain;
        var created_user = data[key].created_user_name;
        var created_at = data[key].created_at;

        var imgstr = '';
        imgstr += '<div class="filebb" id='+id+'>';
        imgstr += '<div class="tu">';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            imgstr += '<img src="'+fileurl+'">';
        }else{
            imgstr += '<div class="zimu">'+fileext+'</div>';
        }
        imgstr += '</div>';
        imgstr += '<div class="titss">'+filename+'</div>';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            // imgstr += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_viewer_imgnew_show(\''+filepath+'\',\''+fileurl+'\')" title="查看"></i>';
            imgstr += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_viewer_img_show(\''+dom+'\')" title="查看"></i>';
        }else if(fileext == 'pdf'){
            imgstr += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')" title="查看"></i>';
        }else if(fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx'){
            imgstr += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_vieweroffice_show(\''+fileurl+'\')" title="查看"></i>';
        }else{
            imgstr += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_show_yulan_not()" title="查看"></i>';
        }

        imgstr += '<i class="layui-icon layui-icon-delete del" onclick="upload_files_del_filenew(this)" title="删除"></i>';
        imgstr += '</div>';


        $('#'+dom+' #fileboxss').append(imgstr);
    }
    upload_files_file_viewer(dom);
}

function public_upload_show_file22(dom, data) {
    var str = '', imgstr = '';
    for (var key in data){
        var id = data[key].id;
        var filename = data[key].name;
        var filepath = data[key].encpath;
        var fileurl = get_file_complete(filepath);
        var fileext = data[key].ext;
        var filesize = data[key].size;
        var fileplain = data[key].fileplain;
        var created_user = data[key].created_user_name;
        var created_at = data[key].created_at;
        var trNum =  parseInt(key)+1;
        str += '<tr id='+id+'>';
        str += '<td>'+trNum+'</td>';
        str += '<td>';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            str += '<div class="file-title" onclick="upload_files_viewer_img_show(\''+dom+'\')"><span>'+filename+'</span></div>';
        }else if(fileext == 'pdf'){
            str += '<div class="file-title" onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')"><span>'+filename+'</span></div>';
        }else if(fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx'){
            str += '<div class="file-title" onclick="upload_files_vieweroffice_show(\''+fileurl+'\')"><span>'+filename+'</span></div>';
        }else{
            str += '<div class="file-title" onclick="upload_files_show_yulan_not()"><span style="color:#666!important;">'+filename+'</span></div>';
        }

        str += '<div class="file-down" onclick="public_down_file(\''+filepath+'\')"><i title="下载" class="layui-icon layui-icon-download-circle"></i></div>';
        str += '</td>';
        str += '<td>'+fileplain+'</td>';
        str += '<td>'+filesize+'KB</td>';
        str += '<td>'+created_at+'</td>';
        str += '<td>'+created_user+'</td>';
        str += '</tr>';


        imgstr += '<div class="img-box" title='+filename+'>';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            imgstr += ' <div class="img-div"><img src="'+fileurl+'" data_src="'+fileurl+'"></div>';
        }else if(fileext == 'pdf'){
            imgstr += ' <div class="img-div" onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')"><div class="dea-img">'+fileext+'</div></div>';
        }else if(fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx'){
            imgstr += ' <div class="img-div" onclick="upload_files_vieweroffice_show(\''+fileurl+'\')"><div class="dea-img">'+fileext+'</div></div>';
        }else{
            imgstr += ' <div class="img-div" onclick="upload_files_show_yulan_not()"><div class="dea-img">'+fileext+'</div></div>';
        }
        imgstr += '<div class="img-filename">'+filename+'</div>';
        imgstr += '</div>';
    }

    if(str == ''){
        str += file_none(6);
    }
    file_assign('#'+dom+' .show_page_file_list', str);
    // $('#'+dom+' .show_page_file_list').html(str);

    if(imgstr == ''){
        $('#'+dom+' .file-list-image').html('<div style="text-align: center;\n' +
            '    padding-top: 9px;\n' +
            '    border: 1px solid #eee;\n' +
            '    padding-bottom: 9px;\n' +
            '    border-top: 0;"><div><img style="width:70px;" src="/static/admin/images/welnodata.png" /></div><span style="color: #aaa;">暂无数据</span></div>');
    }else{
        $('#'+dom+' .show_page_file_div').html(imgstr);
    }

    upload_files_file_viewer(dom);


    // 附件点击隐藏事件
    $('#'+dom+' .title-file .title-icon-table').click(function () {
        $('#'+dom+' .file-list-table').show();
        $('#'+dom+' .file-list-image').hide();
    });
    $('#'+dom+' .title-file .title-icon-image').click(function () {
        $('#'+dom+' .file-list-image').show();
        $('#'+dom+' .file-list-table').hide();
    });
}

function public_upload_show_file(dom, data) {
    var str = '';
    for (var key in data) {
        var id = data[key].id;
        var filename = data[key].name;
        var filepath = data[key].encpath;
        var fileurl = get_file_complete(filepath);
        var fileext = data[key].ext;
        var filesize = data[key].size;
        var fileplain = data[key].fileplain;
        var created_user = data[key].created_user_name;
        var created_at = data[key].created_at;
        var trNum = parseInt(key) + 1;

        str += '<div class="filebb">';
        str += '<div class="tu">';
        if (fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif') {
            str += '<img src="' + fileurl + '">';
            str += '</div>';
            str += '<div class="titss">' + filename + '</div>';
            // str += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_viewer_imgnew_show(\''+filepath+'\',\''+fileurl+'\')" title="查看"></i>';
            str += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_viewer_img_show(\''+dom+'\')" title="查看"></i>';
        } else if (fileext == 'pdf') {
            str += '<div class="zimu">'+fileext+'</div>';
            str += '</div>';
            str += '<div class="titss">' + filename + '</div>';
            str += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')" title="查看"></i>';
        } else if (fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx') {
            str += '<div class="zimu">'+fileext+'</div>';
            str += '</div>';
            str += '<div class="titss">' + filename + '</div>';
            str += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_vieweroffice_show(\''+fileurl+'\')" title="查看"></i>';
        } else {
            str += '<div class="zimu">'+fileext+'</div>';
            str += '</div>';
            str += '<div class="titss">' + filename + '</div>';
            str += '<i class="layui-icon layui-icon-search cha" onclick="upload_files_show_yulan_not()" title="查看"></i>';
        }
        str += '<i class="layui-icon layui-icon-download-circle xia"  onclick="public_down_file(\''+filepath+'\')" title="下载"></i>';
        str += '</div>';
    }

    $("#showPageFiles .filedivv").html(str);
    upload_files_file_viewer(dom);
}

function upload_files_init_mouse(dom) {
    $("#"+dom+" .divkuai .upload_files .image_show .li").on("mouseover",function(){
        $(this).find('.filetit').addClass('colorlan');
        $(this).find('.cheng').show();
        $(this).addClass('lilan');
    });
    $("#"+dom+" .divkuai .upload_files .image_show .li").on("mouseout",function(){
        $(this).find('.filetit').removeClass('colorlan');
        $(this).find('.cheng').hide();
        $(this).removeClass('lilan');
    });
}

function upload_files_qiehuan(dom) {
    $("#"+dom+" .divkuai .tit .files_rightopt .tog_table").click(function () {
        $("#"+dom+" .divkuai .tit .files_rightopt a").removeClass('colorlan');
        $(this).addClass('colorlan');
        $("#"+dom+" .upload_files .table_show").show();
        $("#"+dom+" .upload_files .image_show").hide();
    });
    $("#"+dom+" .divkuai .tit .files_rightopt .tog_image").click(function () {
        $("#"+dom+" .divkuai .tit .files_rightopt a").removeClass('colorlan');
        $(this).addClass('colorlan');
        $("#"+dom+" .upload_files .table_show").hide();
        $("#"+dom+" .upload_files .image_show").show();
    });
}

function upload_files_file_btn(dom, isimg=0){
    layui.use('layer',function(){
        var layer = layui.layer;
        layer.open({
            type: 2,
            title: '上传文件',
            maxmin: true,
            area: ['600px', '400px'],
            content: '../public/upload.php?isimg='+isimg+'&dom='+dom,
            cancel :function (index) {
                layer.confirm("正在上传文件信息，是否直接关闭窗口？",function (conindex) {
                    layer.close(conindex);
                    layer.close(index);
                });
                return false;
            }
        });
    });
}

function upload_files_viewer_img_show(dom){
    viewerObj[dom].show();
}

function upload_files_viewer_imgnew_show(filepath, fileurl) {
    var str = '';

    str += '<style>.scale-slider{position: fixed;right:120px;z-index:99;top:100px}</style>';
    str += '<div class="scale-slider" style="background-color: #FFFFFF">';
    str += '<i onclick="imagesratebai(1)" class="fa fa-minus btn" style="color: #777"></i>';
    str += '<span id="ratebai" key="100">100%</span>';
    str += '<i onclick="imagesratebai(2)" class="fa fa-plus btn" style="color: #777"></i>';
    str += '<span onclick="public_down_file(\''+filepath+'\')" class="colorlan">下载</span>';
    str += '';
    str += '</div>';
    str += '';
    str += '<div id="mapss" style="text-align: center;margin: 100px">';
    str += '<img src="' + fileurl + '">';
    str += '</div>';




    top.parent.layer.open({
        type: 1,
        title: '预览',
        area: ['90%', '100%'],
        maxmin: true,
        // content: '<div class="panel-body"><a class="media" href="'+path+'"></a></div>',
        // content: '<iframe src="'+path+'" frameborder="0" width="100%" height="100%"></iframe>',
        content: str,
        success: function(layero, index){
            // $('a.media').media({width:'99.8%', height:layero[0].clientHeight - 50})
        }
    });
}



function upload_files_viewer_pdf_show(path) {
    top.parent.layer.open({
        type: 1,
        title: '预览',
        area: ['90%', '100%'],
        maxmin: true,
        // content: '<div class="panel-body"><a class="media" href="'+path+'"></a></div>',
        content: '<iframe src="'+path+'" frameborder="0" width="100%" height="100%"></iframe>',
        success: function(layero, index){
            // $('a.media').media({width:'99.8%', height:layero[0].clientHeight - 50})
        }
    });
}

function upload_files_vieweroffice_show(path) {
    layui.use(['laytp'], function() {
        $.ajax({
            url:path,
            type:'get',
            data:{token:facade.getCookie('token')},
            dataType:'json',
            async: false,
            success:function (e) {
                if(e.code == 2000){
                    var urls = "https://view.officeapps.live.com/op/view.aspx?src="+encodeURI(server_doc_name+e.data);
                    top.parent.layer.open({
                        type: 1,
                        title: '预览',
                        area: ['90%', '100%'],
                        maxmin: true,
                        // content: '<div class="panel-body"><a class="media" href="'+path+'"></a></div>',
                        content: '<iframe src="'+urls+'" frameborder="0" width="100%" height="100%"></iframe>',
                        success: function(layero, index){
                            // $('a.media').media({width:'99.8%', height:layero[0].clientHeight - 50})
                        }
                    });
                }
            }
        });
    });
}

function upload_files_show_yulan_not() {
    facade.error("此文件类型不支持预览,请下载查看");
}


function get_yulan_bao_file(ext, encpath){
    if(ext == 'png' || ext == 'pneg' || ext == 'jpg' || ext == 'jpeg' || ext == 'gif'){
        upload_files_viewer_imgnew_show(encpath, get_bao_file_complete(encpath));
    }else if(ext == 'pdf'){
        upload_files_viewer_pdf_show(get_bao_file_complete(encpath))
    }else if(ext == 'doc' || ext == 'docx' || ext == 'xls' || ext == 'xlsx' || ext == 'ppt' || ext == 'pptx'){
        upload_files_vieweroffice_show(get_bao_file_complete(encpath))
    }else{
        upload_files_show_yulan_not();
    }
}



function upload_files_file_viewer(dom){
    try {
        viewerObj[dom].destroy();
    }catch (e) {

    }
    viewerObj[dom] = new Viewer(document.getElementById(dom));
}

function upload_files_del_file(dom, id){
    layer.confirm('确定要删除该文件吗？',function(index){
        $("#"+dom+" .upload_files .table_show tbody tr").each(function () {
            if($(this).attr('id') == id){
                $(this).remove();
            }
        });
        $("#"+dom+" .upload_files .image_show .li").each(function () {
            if($(this).attr('id') == id){
                $(this).remove();
            }
        });
        upload_files_file_viewer(dom);
        layer.close(index);
    });
}
function upload_files_del_filenew(obj){
    layer.confirm('确定要删除该文件吗？',function(index){
        $(obj).parents('.filebb').remove();
        layer.close(index);
    });
}



function public_min_file_load(dom, data=[], tits='上传附件') {
    $("#"+dom).find('.min-tits').text(tits);

    if(data.length > 0){
        //此处处理编辑数据。。。  暂未遇到。。
    }

    $("#"+dom).find('.upload_file_btn').click(function () {
        upload_min_file_btn(dom);
    });
    upload_min_init_mouse(dom);
}

function public_min_file_value(dom) {
    var files = [];
    $('#'+dom+' .show-minimg .li').each(function(){
        var fileid = $(this).attr('id') || '';
        if(fileid){
            files.push(fileid);
        }
    });
    return files.join(',');
}

function upload_min_init_mouse(dom) {
    $("#"+dom+" .show-minimg .li").on("mouseover",function(){
        $(this).find('.filetit').addClass('colorlan');
        $(this).find('.cheng').show();
        $(this).addClass('lilan');
    });
    $("#"+dom+" .show-minimg .li").on("mouseout",function(){
        $(this).find('.filetit').removeClass('colorlan');
        $(this).find('.cheng').hide();
        $(this).removeClass('lilan');
    });
}

function upload_min_file_btn(dom, isimg=0){
    layui.use('layer',function(){
        var layer = layui.layer;
        layer.open({
            type: 2,
            title: '上传文件',
            maxmin: true,
            area: ['600px', '400px'],
            content: '../public/upload_min.php?isimg='+isimg+'&dom='+dom,
            cancel :function (index) {
                layer.confirm("正在上传文件信息，是否直接关闭窗口？",function (conindex) {
                    layer.close(conindex);
                    layer.close(index);
                });
                return false;
            }
        });
    });
}

function upload_min_file_viewer(dom){
    try {
        viewerMinObj.destroy();
    }catch (e) {

    }
    viewerMinObj = new Viewer(document.getElementById(dom));
}

function upload_min_del_file(dom, id){
    layer.confirm('确定要删除该文件吗？',function(index){
        $("#"+dom+" .show-minimg .li").each(function () {
            if($(this).attr('id') == id){
                $(this).remove();
            }
        });

        upload_min_file_viewer(dom);
        layer.close(index);
    });
}

function public_down_file(encpath) {
    let btnDownload = document.createElement('a'),
        clickEvent = document.createEvent("MouseEvent");

    let url = server_api_name+ask_down_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
    clickEvent.initEvent("click", true, false);
    btnDownload.setAttribute("href", url);
    btnDownload.setAttribute("target", '_blank');
    btnDownload.dispatchEvent(clickEvent);
}

function public_down_bao_file(encpath) {
    let btnDownload = document.createElement('a'),
        clickEvent = document.createEvent("MouseEvent");

    let url = server_api_name+ask_down_bao_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
    clickEvent.initEvent("click", true, false);
    btnDownload.setAttribute("href", url);
    btnDownload.setAttribute("target", '_blank');
    btnDownload.dispatchEvent(clickEvent);
}
function public_down_ban_file(encpath) {
    let btnDownload = document.createElement('a'),
        clickEvent = document.createEvent("MouseEvent");

    let url = server_api_name+ask_down_ban_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
    clickEvent.initEvent("click", true, false);
    btnDownload.setAttribute("href", url);
    btnDownload.setAttribute("target", '_blank');
    btnDownload.dispatchEvent(clickEvent);
}
function public_down_temp_file(encpath) {
    let btnDownload = document.createElement('a'),
        clickEvent = document.createEvent("MouseEvent");

    let url = server_api_name+ask_down_temp_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
    clickEvent.initEvent("click", true, false);
    btnDownload.setAttribute("href", url);
    btnDownload.setAttribute("target", '_blank');
    btnDownload.dispatchEvent(clickEvent);
}


function public_down_engin_file(encpath) {
    let btnDownload = document.createElement('a'),
        clickEvent = document.createEvent("MouseEvent");

    let url = server_api_name+ask_down_engin_file+'dd/'+encpath+'/token/'+facade.getCookie('token')
    clickEvent.initEvent("click", true, false);
    btnDownload.setAttribute("href", url);
    btnDownload.setAttribute("target", '_blank');
    btnDownload.dispatchEvent(clickEvent);
}

function IsExstsFile(filedir) {
    var xmlhttp;
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }else if (window.ActiveXObject){
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) { }
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) { }
        if (!xmlhttp) {
            return false;
        }
    }
    xmlhttp.open("GET",filedir,false);
    xmlhttp.send();
    if(xmlhttp.readyState==4){
        if(xmlhttp.status==200){
            return true;
        } else{
            return false;
        }

    }
    return false;
}

function load_areas(dom, data, level=1, isid=false) {
    if (typeof window !== 'undefined') {
        window.ChineseDistricts = data;
    }

    var level_name = 'provinceId';
    if(level == 2){
        level_name = 'cityId';
    }
    if(level == 3){
        level_name = 'districtId';
    }

    layui.extend({
        citypicker:'cityPicker/city-picker'
    }).use(['citypicker'], function() {
        var citypicker = layui.citypicker;
        if(isid){
            var cityPicker = new citypicker("#"+dom,{
                provincename:"provinceId",
                cityname:"cityId",
                districtname: "districtId",
                level: level_name,
            })
        }else{
            var cityPicker = new citypicker("#"+dom,{
                level: level_name,
            })
        }
    });
}


function formValid(cls, msg = '请选择'){
    var check_key = $("#"+cls).attr('key') || 0;
    if(check_key > 0){
        if($("#"+cls).find('button').length > 0){
            $('.'+cls).parent().find('input').removeClass('border_color_red').parents('.layui-input-block').find('p').remove();
        }else{
            if(msg == ''){
                $('.'+cls).parent().find('input').removeClass('border_color_red').parents('.layui-input-block').find('p').remove();
            }else{
                $('.'+cls).parent().find('input').removeClass('border_color_red').parents('.layui-input-block').find('p').remove();
                $('.'+cls).parent().find('input').addClass('border_color_red').parents('.layui-input-block').append('<p class="error_info">'+msg+'</p>');
            }
        }
    }
}

function set_choose_btn_more(id, arr){
    for (var key in arr){
        set_choose_btn(id,arr[key].id,arr[key].modename+'【'+arr[key].sericnum+'】');
    }
}

function set_choose_btn_more_other(id, arr){
    for (var key in arr){
        set_choose_btn(id,arr[key].id,arr[key].name);
    }
}

function set_choose_btn(id, key, name, msg = ''){
    if(!key){
        return true;
    }
    if(msg === ''){
        var str = '<button class="layui-btn layui-btn-sm" style="width: auto;max-width: 95%;" type="button" key="'+key+'">'+name+'' +
            '<span class="choose_close" onclick="choose_close(this, \''+id+'\')">×</span></button>';
    }else{
        var str = '<button class="layui-btn layui-btn-sm" style="width: auto;max-width: 95%;" type="button" key="'+key+'">'+name+'' +
            '<span class="choose_close" onclick="choose_close(this, \''+id+'\', \''+msg+'\')">×</span></button>';
    }
    $('#'+id).append(str);
}

function closeTanTag(obj) {
    $(obj).parent('div.tags').remove();
}
function tan_tags_init(dom, data) {
    var str = '';
    for (var key in data){
        data[key].part = data[key].part || '';
        str += '<div class="tags">';
        str += '<div ' +
            'title="'+data[key].name+'" '+
            'data-id="'+data[key].id+'" '+
            'data-part="'+data[key].part+'" '+
            '>';
        str += data[key].name+'</div>';
        str += '<i class="layui-icon" onclick="closeTanTag(this)">&#x1006;</i></div>';
    }
    $(dom).html(str);
}
function tan_tags_getvalue(dom, type='user') {
    var data = [];
    $(dom+' .tags').each(function () {
        var part = $(this).children('div').attr('data-part');
        var id = $(this).children('div').attr('data-id');
        if(type == 'user' && part == 'user'){
            data.push(id);
        }
        if(type == 'dept' && part == 'dept'){
            data.push(id);
        }
        if(type == 'part' && (part == 'user' || part == 'dept')){
            data.push(part+id);
        }
    });
    return data.join(',');
}
function tan_tags_getname(dom, type='user') {
    var data = [];
    $(dom+' .tags').each(function () {
        var value = $(this).children('div').text();
        if(value){
            data.push(value);
        }
    });
    return data.join(',');
}



/**
 * 数字转中文
 * @param dValue
 * @returns
 */
function chineseNumber(dValue,maxDec) {
    if(maxDec == undefined || maxDec == false){
        maxDec = 2;
    }
    // 验证输入金额数值或数值字符串：
    dValue = dValue.toString().replace(/,/g, "");
    dValue = dValue.replace(/^0+/, ""); // 金额数值转字符、移除逗号、移除前导零
    if (dValue == "") {
        return "零元整";
    } // （错误：金额为空！）
    else if (isNaN(dValue)) {
        return "错误：金额不是合法的数值！";
    }
    if(maxDec == 6){
        dValue = dValue*10000 + '';
        maxDec = 2;
    }
    var minus = ""; // 负数的符号“-”的大写：“负”字。可自定义字符，如“（负）”。
    var CN_SYMBOL = ""; // 币种名称（如“人民币”，默认空）
    if (dValue.length > 1) {
        if (dValue.indexOf('-') == 0) {
            dValue = dValue.replace("-", "");
            minus = "负";
        } // 处理负数符号“-”
        if (dValue.indexOf('+') == 0) {
            dValue = dValue.replace("+", "");
        } // 处理前导正数符号“+”（无实际意义）
    }
    // 变量定义：
    var vInt = "";
    var vDec = ""; // 字符串：金额的整数部分、小数部分
    var resAIW; // 字符串：要输出的结果
    var parts; // 数组（整数部分.小数部分），length=1时则仅为整数。
    var digits, radices, bigRadices, decimals; // 数组：数字（0~9——零~玖）；基（十进制记数系统中每个数字位的基是10——拾,佰,仟）；大基（万,亿,兆,京,垓,杼,穰,沟,涧,正）；辅币（元以下，角/分/厘/毫/丝）。
    var zeroCount; // 零计数
    var i, p, d; // 循环因子；前一位数字；当前位数字。
    var quotient, modulus; // 整数部分计算用：商数、模数。
    // 金额数值转换为字符，分割整数部分和小数部分：整数、小数分开来搞（小数部分有可能四舍五入后对整数部分有进位）。
    var NoneDecLen = (typeof (maxDec) == "undefined" || maxDec == null || Number(maxDec) < 0 || Number(maxDec) > 5); // 是否未指定有效小数位（true/false）
    parts = dValue.split('.'); // 数组赋值：（整数部分.小数部分），Array的length=1则仅为整数。
    if (parts.length > 1) {
        vInt = parts[0];
        vDec = parts[1]; // 变量赋值：金额的整数部分、小数部分
        if (NoneDecLen) {
            maxDec = vDec.length > 5 ? 5 : vDec.length;
        } // 未指定有效小数位参数值时，自动取实际小数位长但不超5。
        var rDec = Number("0." + vDec);
        rDec *= Math.pow(10, maxDec);
        rDec = Math.round(Math.abs(rDec));
        rDec /= Math.pow(10, maxDec); // 小数四舍五入
        var aIntDec = rDec.toString().split('.');
        if (Number(aIntDec[0]) == 1) {
            vInt = (Number(vInt) + 1).toString();
        } // 小数部分四舍五入后有可能向整数部分的个位进位（值1）
        if (aIntDec.length > 1) {
            vDec = aIntDec[1];
        } else {
            vDec = "";
        }
    } else {
        vInt = dValue;
        vDec = "";
        if (NoneDecLen) {
            maxDec = 0;
        }
    }
    if (vInt.length > 44) {
        return "错误：金额值太大了！整数位长【" + vInt.length.toString() + "】超过了上限——44位/千正/10^43（注：1正=1万涧=1亿亿亿亿亿，10^40）！";
    }
    // 准备各字符数组 Prepare the characters corresponding to the digits:
    digits = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); // 零~玖
    radices = new Array("", "拾", "佰", "仟"); // 拾,佰,仟
    bigRadices = new Array("", "万", "亿", "兆", "京", "垓", "杼", "穰", "沟", "涧", "正"); // 万,亿,兆,京,垓,杼,穰,沟,涧,正
    decimals = new Array("角", "分", "厘", "毫", "丝"); // 角/分/厘/毫/丝
    resAIW = ""; // 开始处理
    // 处理整数部分（如果有）
    if (Number(vInt) > 0) {
        zeroCount = 0;
        for (i = 0; i < vInt.length; i++) {
            p = vInt.length - i - 1;
            d = vInt.substr(i, 1);
            quotient = p / 4;
            modulus = p % 4;
            if (d == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    resAIW += digits[0];
                }
                zeroCount = 0;
                resAIW += digits[Number(d)] + radices[modulus];
            }
            if (modulus == 0 && zeroCount < 4) {
                resAIW += bigRadices[quotient];
            }
        }
        if(maxDec == 2){
            resAIW += "元";
        }else{
            resAIW += "万元";
        }
    }
    // 处理小数部分（如果有）
    for (i = 0; i < vDec.length; i++) {
        d = vDec.substr(i, 1);
        if (d != "0") {
            resAIW += digits[Number(d)] + decimals[i];
        }
    }
    // 处理结果
    if (resAIW == "") {
        resAIW = "零" + "元";
    } // 零元
    if (vDec == "") {
        resAIW += "";
    } // ...元整
    resAIW = CN_SYMBOL + minus + resAIW; // 人民币/负......元角分/整
    return resAIW;
}

/**
 * 数字转三个数字一个逗号格式
 */
function parseFormatNum(number,n){
    if(!number){
        number = 0;
    }
    var fu = 0;
    if(parseFloat(number) < 0){
        number = -number;
        fu = 1;
    }
    if(n != 0 ){
        n = (n > 0 && n <= 20) ? n : 2;
    }
    number = parseFloat((number + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var sub_val = number.split(".")[0].split("").reverse();
    var sub_xs = number.split(".")[1];
    var show_html = "";
    for (i = 0; i < sub_val.length; i++){
        show_html += sub_val[i] + ((i + 1) % 3 == 0 && (i + 1) != sub_val.length ? "," : "");
    }

    if(n == 0 ){
        if(fu === 1){
            return '-'+show_html.split("").reverse().join("");
        }else{
            return show_html.split("").reverse().join("");
        }
    }else{
        if(fu === 1){
            return '-'+show_html.split("").reverse().join("") + "." + sub_xs;
        }else{
            return show_html.split("").reverse().join("") + "." + sub_xs;
        }
    }
}

/**
 * 获取 有效 数字
 */
function parseValidNum(num, n=2) {
    if(!num){
        return 0;
    }

    num = parseFormatNum(num, n);
    num = parseNum(num);

    if(isNaN(num)){
        return 0;
    }

    num = parseFloat(num);
    return num.toFixed(n);
}

/**
 * 三个数字一个逗号格式 转化为数字
 * @param number
 * @returns {string}
 */
function parseNum(number) {
    var arr = number.split(",");
    var money = '';
    for (var i=0;i<arr.length;i++){
        money += arr[i];
    }
    return money;
}

// 提交处理金额
function parseMoney(data) {
    $('.moneyinput').each(function (i) {
        var id = $(this).attr('id');
        data.field[id] = parseNum(data.field[id])
    });
    $('.moneyinput6').each(function (i) {
        var id = $(this).attr('id');
        data.field[id] = parseNum(data.field[id])
    });
    return data;
}

function initParseMoney() {
    $('.moneyinput').each(function () {
        var m = $(this).val();
        if(m != ''){
            $(this).val(parseFormatNum(m,2));
        }
    });
    $('.moneyinput6').each(function () {
        var m = $(this).val();
        if(m != ''){
            $(this).val(parseFormatNum(m,6));
        }
    });
}

// 金额获取焦点
function mFocus(obj, n){
    var m = $(obj).val();
    var dm = '';
    var width = $(obj).width() + 34;
    var left = $(obj).offset().left;
    var top = $(obj).offset().top - $(window).scrollTop() + 36;
    if(m == ''){
        str = '<div id="moneyDiv" style="position: fixed;width:'+width+'px;height: 47px;padding:5px;' +
            'background: #fff;border: 1px solid #ccc;left:'+left+'px;top:'+top+'px;display: none;"></div>';
    }else{
        dm = chineseNumber(m, n);
        var money = parseNum(m);
        $(obj).val(money);
        str = '<div id="moneyDiv" style="position: fixed;width:'+width+'px;height: 47px;padding:5px;' +
            'background: #fff;border: 1px solid #ccc;left:'+left+'px;top:'+top+'px;">'+dm+'</div>';
    }
    $('body').append(str);

    $(window).scroll(function() {
        var top = $(obj).offset().top - $(window).scrollTop() + 36;
        $('body').find('#moneyDiv').css('top',top+'px')
    });

    $(obj).on('input propertychange',function () {
        var m = $(this).val();
        var dm = chineseNumber(m, n);
        $('body').find('#moneyDiv').show().html(dm);
    });
}
// 金额失去焦点
function mBlur(obj, n){
    var m = $(obj).val();
    var rule = /\d/;
    if(rule.test(m)){
        $(obj).val(parseFormatNum(m, n));
    }else{
        $(obj).val('');
    }
    $('body').find('#moneyDiv').remove();
}

// 处理明细选中后出现背景消失
function reload_table_list_bac(ele, current) {
    if(current == undefined || current == false){
        $('.'+ele+' tr').each(function (i) {
            // 选中行处理
            if($(this).find('td:first-child').attr('class') == 'rowchoose'){
                $(this).find('.layui-unselect input').each(function (ii) {
                    $(this).css({"background": "#cbeaed"});
                })
            }else{
                // 选中列处理
                $(this).find('.colchoose input').css({"background": "#cbeaed"});
            }
        })
    }else{
        $('.'+ele+' tr', parent.document).each(function (i) {
            // 选中行处理
            if($(this).find('td:first-child').attr('class') == 'rowchoose'){
                $(this).find('.layui-unselect input').each(function (ii) {
                    $(this).css({"background": "#cbeaed"});
                })
            }else{
                // 选中列处理
                $(this).find('.colchoose input').css({"background": "#cbeaed"});
            }
        })
    }
}


function strpos(haystack, needle, start) {
    if (typeof(start)==="undefined") {
        start = 0;
    }
    if (!needle) {
        return 0;
    }
    var j = 0;
    for (var i = start; i < haystack.length && j < needle.length; i++) {
        if (haystack.charAt(i) === needle.charAt(j)) {
            j++;
        } else {
            j = 0;
        }
    }
    if (j === needle.length) {
        return i - needle.length;
    }
    return -1;
}

// 下载文件
function down_file(urlname) {
    let btnDownload = document.createElement('a'),
        clickEvent = document.createEvent("MouseEvent");
    let url = server_api_name + "/" + urlname;
    clickEvent.initEvent("click", true, false);
    btnDownload.setAttribute("href", url);
    btnDownload.setAttribute("target", '_blank');
    btnDownload.dispatchEvent(clickEvent);
}



function public_show_file_deta(listdom, filearr, isdel=1, nums='') {
    if(!filearr){
        filearr = [];
    }

    var str = '';
    str += '<div class="upload_deta_divs upload_deta_con'+nums+'">';
    for (var key in filearr){
        var fileext = filearr[key].ext;
        var filename = filearr[key].name;
        var fileurl = get_file_complete(filearr[key].encpath);

        str += '<div fileid="'+filearr[key].id+'">';
        if(fileext == 'png' || fileext == 'pneg' || fileext == 'jpg' || fileext == 'jpeg' || fileext == 'gif'){
            str += '<span onclick="upload_files_deta_viewer_img_show(\''+listdom+'\')">'+filename+'</span>';
            str += '<img class="detaimg'+filearr[key].id+'" src="'+fileurl+'" style="height: 0" data_src="'+fileurl+'">';
        }else if(fileext == 'pdf'){
            str += '<span onclick="upload_files_viewer_pdf_show(\''+fileurl+'\')">'+filename+'</span>';
        }else if(fileext == 'doc' || fileext == 'docx' || fileext == 'xls' || fileext == 'xlsx' || fileext == 'ppt' || fileext == 'pptx'){
            str += '<span onclick="upload_files_vieweroffice_show(\''+fileurl+'\')">'+filename+'</span>';
        }else{
            str += '<span onclick="upload_files_show_yulan_not()">'+filename+'</span>';
        }
        if(isdel > 0){
            str += '<i class="fa fa-times-circle shan" onclick="public_list_file_deta_del(this, \''+listdom+'\')"></i>';
        }else{
            str += '<i class="layui-icon layui-icon-download-circle" onclick="public_down_file(\''+filearr[key].encpath+'\')"></i>';
        }
        str += '</div>';
    }
    str += '</div>';

    if(isdel > 0){
        str += '<div class="upload_deta_btn" onclick="public_list_file_deta(\''+listdom+'\',this, \''+nums+'\')"><b>上传</b></div>';
    }

    setTimeout(function () {
        upload_files_deta_file_viewer(listdom);
    },200);
    return str;
}

function public_list_file_deta_del(obj, dom){
    layer.confirm('确定要删除该文件吗？',function(index){
        $(obj).parent('div').remove();
        upload_files_deta_file_viewer(dom)
        layer.close(index);
    });
}

function public_list_file_deta(listdom, thisDom, nums='') {
    var trIndex = $(thisDom).parents('tr').index();
    layer.open({
        type: 2,
        title: '上传文件',
        maxmin: true,
        area: ['600px', '400px'],
        content: '../public/upload_deta.php?listdom='+listdom+'&trIndex='+trIndex+'&nums='+nums,
        cancel :function (index) {
            layer.confirm("正在上传文件信息，是否直接关闭窗口？",function (conindex) {
                layer.close(conindex);
                layer.close(index);
            });
            return false;
        }
    });

}

function public_deta_file_value(obj, nums='') {
    var files = [];
    $(obj).find('.upload_deta_con'+nums).find('div').each(function(){
        var fileid = $(this).attr('fileid') || '';
        if(fileid){
            files.push(fileid);
        }
    });
    return files.join(',');
}

function upload_files_deta_file_viewer(dom){
    try {
        window.viewerDetaObj[dom].destroy();
    }catch (e) {

    }
    if(!window.viewerDetaObj){
        window.viewerDetaObj = [];
    }
    window.viewerDetaObj[dom] = new Viewer(document.getElementById(dom));
}


function upload_files_deta_viewer_img_show(dom){
    window.viewerDetaObj[dom].show();
}













function getChineseDateTime() {
    var date = new Date();
    var sign2 = ":";
    var year = date.getFullYear() // 年
    var month = date.getMonth() + 1; // 月
    var day = date.getDate(); // 日
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
    var week = weekArr[date.getDay()];
    // 给一位数的数据前面加 “0”
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    // return year + "年" + month + "月" + day + "日" + hour + sign2 + minutes + sign2 + seconds;
    return year + "年" + month + "月" + day + "日" + hour + sign2 + minutes;
}




// // 处理多页面点击空白处关闭菜单并处理样式
$(document).bind('click', function(e) {
    var e = e || window.event;
    var elem = e.target || e.srcElement;
    while (elem) {
        if ($(e.target).parents('#sideMenu').length != 0) {
            return;
        }
        elem = elem.parentNode;
    }
    try {
        top.parent.colseSideStyle();
    } catch {

    }
});




function imagesratebai(type) {
    var key = parseInt($("#ratebai").attr('key'));
    if(type == 1){
        if(key <= 5){
            return false;
        }
        var ratebai = key-5;
    }else{
        if(key >= 200){
            return false;
        }
        var ratebai = key+5;
    }
    $("#mapss").css('transform','scale('+(ratebai/100)+')');
    $("#ratebai").html(ratebai+'%').attr('key', ratebai);
}




function ctrlv_data_open(ctrlv_field_name='ctrlv_field_name', ctrlv_data_show='ctrlv_data_show') {
    openPage('../public/ctrlv.php?ctrlv_field_name='+ctrlv_field_name+'&ctrlv_data_show='+ctrlv_data_show, '888px', '555px');
}


function zhuan_str_date(dateString){
    if(dateString.trim()==""){
        return '';
    }
    dateString = dateString.toString().replace(/\//g, '-');
    var r=dateString.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if(r==null){
        return '';
    }
    var d=new Date(r[1],r[3]-1,r[4]);
    var num = (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
    if(num==0){
        return '';
    }
    return dateString;
}




function getCurtime() {
    var date = new Date();
    year = date.getFullYear();
    month = date.getMonth() + 1;
    day = date.getDate();
    hours = date.getHours();
    minutes = date.getMinutes();
    seconds = date.getSeconds();

    month = month < 10 ? '0'+month : month;
    day = day < 10 ? '0'+day : day;
    hours = hours < 10 ? '0'+hours : hours;
    minutes = minutes < 10 ? '0'+minutes : minutes;
    seconds = seconds < 10 ? '0'+seconds : seconds;
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}



function str_in_array(search,array){
    for(var i in array){
        if(array[i]==search){
            return true;
        }
    }
    return false;
}


function curMoveTables(pardom, boxdom) {
    $(".layui-table-box").append('<div id="'+boxdom+'"></div>');
    $(".layui-table-box .layui-table-body").attr('id',pardom);
    var oPanel = document.getElementById(pardom);
    var oDragIcon = document.getElementById(boxdom);
    var disX = 0;
    var disY = 0;
    var disW = 0;
    var disH = 0;
    oDragIcon.onmousedown = function (ev) {
        var ev = ev || window.event;
        disX = ev.clientX;
        disY = ev.clientY;
        disW = oPanel.offsetWidth;
        disH = oPanel.offsetHeight;
        document.onmousemove = function (ev) {
            var ev = ev || window.event;
            var W = ev.clientX - disX + disW;
            var H = ev.clientY - disY + disH;
            if (W < 100)  W = 100;
            if (W > 1800) W = 1800;
            if (H < 100) H = 100;
            if (H > 1000) H = 1000;
            // oPanel.style.height = H + 'px!important';
            $("#"+pardom).attr('style','height:'+H+'px!important')
        }
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
}
function drag_column(dom) {
    //用来存储当前更改宽度的Table Cell,避免快速移动鼠标的问题
    var tTD;
    var table = document.getElementById(dom);
    for (j = 0; j < table.rows[0].cells.length; j++) {
        table.rows[0].cells[j].onmousedown = function () {
            if($(this).attr('drag') == 'fasle'){
                return false;
            }
            //记录单元格
            tTD = this;
            if (event.offsetX > tTD.offsetWidth - 10) {
                tTD.mouseDown = true;
                tTD.oldX = event.x;
                tTD.oldWidth = tTD.offsetWidth;
            }
            // 记录Table宽度
            // table = tTD; while (table.tagName != 'TABLE') table = table.parentElement;
            // tTD.tableWidth = table.offsetWidth;
        };
        table.rows[0].cells[j].onmouseup = function () {
            //结束宽度调整
            if (tTD == undefined) tTD = this;
            tTD.mouseDown = false;
            tTD.style.cursor = 'default';
        };
        table.rows[0].cells[j].onmousemove = function () {
            //更改鼠标样式
            if (event.offsetX > this.offsetWidth - 10)
                this.style.cursor = 'col-resize';
            else
                this.style.cursor = 'default';
            //取出暂存的Table Cell
            if (tTD == undefined) tTD = this;

            //调整宽度
            if (tTD.mouseDown != null && tTD.mouseDown == true) {
                tTD.style.cursor = 'default';
                if (tTD.oldWidth + (event.x - tTD.oldX)>0)
                    tTD.width = tTD.oldWidth + (event.x - tTD.oldX);
                //调整列宽
                tTD.style.width = tTD.width;
                tTD.style.cursor = 'col-resize';
                //调整该列中的每个Cell
                table = tTD; while (table.tagName != 'TABLE') table = table.parentElement;

                // var newWidth = parseInt(tTD.width)+7;

                for (j = 0; j < table.rows.length; j++) {
                    table.rows[j].cells[tTD.cellIndex].style="width:"+tTD.width+"px"

                    // table.rows[j].cells[tTD.cellIndex].width = tTD.width;
                }
                //调整整个表
                // table.width = tTD.tableWidth + (tTD.offsetWidth – tTD.oldWidth);
                // table.style.width = table.width;
            }
        };
    }
}

function removeTrailingZeros(number) {
    if (number === '') {
        return 0
    } else {
        if (number.toString().includes('.')) {
            return parseFloat(number)
        } else {
            return number
        }

    }
}

function mathStrNumber(str, n=2) {
    if(!str){
        return 0;
    }
    if(str.substr(0,1) == '='){
        str = str.substr(1);
    }

    try {
        var resval = math.evaluate(str) || 0;
        return mathRound(resval, n);
    }catch (e) {
        return mathRound(0, n);
    }
}

function mathRound(value, n=2) {
    var resval = Math.round(value * Math.pow(10, n)) / Math.pow(10, n) || 0;
    // return Number(resval).toFixed(n);
    return removeTrailingZeros(Number(resval).toFixed(n));
}
